﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Micro.Extensions.Cache.QuickStart.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;


        private readonly ICacheClient cacheClient;
        public WeatherForecastController(ILogger<WeatherForecastController> logger, ICacheClient cacheClient)
        {
            _logger = logger;
            this.cacheClient = cacheClient;
        }

        [HttpGet]
        public async Task<List<WeatherForecast>> GetAsync()
        {
            var resutl = await  cacheClient.GetAsync<List<WeatherForecast>>("mykey");
            if (!resutl.HasValue)
            {
                var rng = new Random();
                var data = Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = rng.Next(-20, 55),
                    Summary = Summaries[rng.Next(Summaries.Length)]
                })
                .ToList();
               await cacheClient.SetAsync("mykey", data, 300);
                return data;
            }

            return resutl.Value;

        }
    }
}
